<template>
        <div class="main_topWarp">
                <van-icon class="topWarp_back_btn"  @click="goBack()" name="arrow-left" />
            <div >
                <span class="topWarp_title">{{myDataParams.shareName}}</span>
            </div>
        </div>
        <!-- 搜索 -->
        <div class="dataBoard_search">
            <div v-for="(item,index) in lookForData" class="dataBoard_search_item">
                <!-- <div  v-if="item.inputType=='单选'" @click.stop=" handleLabelClick(item)"> {{item.conditionName}}  {{selectedValues[item.id] || item.defaultValue}}<van-icon name="arrow" ></van-icon> </div> -->
                <div  v-if="item.inputType=='单选'" >
                    <van-field
                        :label="item.conditionName"
                        v-model="selectedValues[item.id]"
                        placeholder="点击选择"
                        @click.stop=" handleLabelClick(item)"
                        readonly clickable
                    />
                </div>
                <!-- 下方弹框 -->
                <template v-if=" showCalendar">
                    <van-popup v-model:show="showCalendar" round position="bottom">
                        <van-picker title="选择筛选条件" :columns="computedPickerColumns "
                            @confirm="(value) => onPickerConfirm(value, item.id)" 
                            @cancel="cancelPick"
                        />
                    </van-popup>
                </template>
                <!-- 多选 -->
                <!-- 输入类型 -->
                <div  v-if="item.inputType === '输入'">
                    <van-field
                        :label="item.conditionName"
                        v-model="selectedValues[item.id]"
                        placeholder="请输入"
                        @blur="handleInputBlur(item.id)"
                        clearable
                        @clear="handleClear(item.id)"
                    />
                </div>
                
            </div>
        </div>
        <!-- 表格及分页 -->
        <div class="dataBoard_TabelBox" v-if="currentPageData.length !== 0" >
            <div class="title"><img src="@/assets/img/DataManagement/juxing.png" alt=""><div>{{tableTitle}}</div></div>
            <div class="content">
                <div class="table-container">
                    <table  v-if="currentPageData&&currentPageData.length>0">
                        <thead>
                            <div class="thead-wrap" ref="theadWrap">
                                <tr  class="tr_theadNew">  
                                    <th class="td_theadNew fixed-left staticCol" >序号</th>  
                                    <th class="scrollable-theadContent"  v-for="(value, key) in Object.keys(currentPageData[0])" :key="key">{{value}}</th>
                                </tr>
                            </div>
                        </thead>
                        <tbody>
                            <div class="tbody-wrap" ref="tbodyWrap">
                                <tr  v-for="(item, rowIndex) in currentPageData" :key="rowIndex" class="tr_new">
                                    <td class="td_new tbody-fixed-left staticCon" >{{ rowIndex + 1 }}</td>  
                                    <td class="scrollable-content" v-for="key in Object.keys(item)" :key="key">{{ item[key] || '--'}}</td>
                                </tr>
                            </div>
                        </tbody>
                    </table>
                    <table v-else>
                        <div slot="no-results" class="noData" >
                            <div class="noData_container">
                                <img src="@/assets/img/home/kanban.png" alt="">
                                <div>暂无数据</div>
                            </div>
                        </div>
                    </table>
                </div>

                <!-- 分页 -->
                <div class="myPagination">
                    <van-pagination 
                        class="inner_pagination"
                        v-model="currentPage" 
                        :total-items="total" 
                        :items-per-page="itemsPerPage"
                        :show-page-size="3" 
                        force-ellipses
                        @change="onPageChange" 
                    />
                    <!-- @change="onPageChange" -->
                </div> 

            </div>
        </div>



</template>

<script>
import { onBeforeMount, onMounted, reactive, ref, toRefs,watch,onUnmounted,computed  } from 'vue'
import { Toast, Notify} from 'vant';
import { useStore } from "vuex"; // ⚪️ 引入状态管理
import router from "@/router";
import { useRoute } from 'vue-router';
import { ShareDataGetShareFields, } from "@/network/DataManagement.js";
import { StoryBoardGetMobileData, StoryBoardGetConditionCascadeData} from "@/network/StoryBoard.js";


export default {
    
    setup() {
        // 获取当前路由信息
        const route = useRoute();
        const state = reactive({
            isLoading: false,
            myDataParams: route.query,
            fieldsData: [], // 后端返回的数据
            newFieldsData: [], // 前端生成数据
            storyParams:{ //查询参数
                pageIndex:'1',
                storyID: route.query.Id, //表示故事板ID
                storyTableID: "", //表示故事板的表的ID 596993a9-cc42-438d-9e56-3b759ff45911
                inputConditions: [ //用户输入的条件
                    // { name: "",	//条件的ID
                    //   value: ""		//条件的值
                    // }
                ],
                parentConditions: [],//下钻界面的上级数据作为条件
                dependencyValue: ""  //依赖值：比如城市，依赖值是某个省份，如湖南省，就表示为湖南省下面的所有城市
            }, 
            // 输入条件
            inputCondition:[],
            
            // 条件数据
            lookForData:[],
            currentItemId :null, //状态变量来存储当前点击项的 id
            selectedValues:{}, // 存储选中的值

            // 添加一个状态来保存搜索参数
            searchParams: {},

            // ==================
            searchDate:new Date(), //搜索日期
            showCalendar:false, //是否展示日期选择弹框
            

            // 表格名称
            tableTitle:'',
            // 表格数据
            tableData:[],
            
            // 分页器
            currentPage:1,
            total:0, //在搜索获取数据列表时，更新获取到的总条数
            perPage:'',//每页展示数量
            completeData:[], // 完整数据集
            currentPageData :[], // 当前页的数据
            itemsPerPage :20, // 每页显示的项目数量

        })
        let pickerOptions = reactive([]); // 筛选条件的值
        // 表单生成相关
        const formData = reactive([]);
        /*****************state**end*************************/ 
        // 计算属性来处理当pickerOptions为空时的显示
        const computedPickerColumns = computed(() => {
            // 直接返回 pickerOptions 或默认数组
            if (pickerOptions.length > 0) {
                
                return pickerOptions;
            }
            return [{ text: '暂无更多筛选条件', disabled: true }];
        });

        // 初始化挂载
        onMounted(() => {
            // 获取数据
            getInitlookForData()
            setTimeout(() => {
                state.lookForData.forEach((item) => {
                    state.selectedValues[item.id] = item.defaultValue || '';
                });
                buildSearchParams()
                // 获取数据
                getInitDataList()
            }, 500);
            // 初始化当前页数据 （之前是返回所有数据，现在直接返回分页故不需要了）
            // updateCurrentPageData(state.currentPage);
            // console.log('传过来的数据',state.myDataParams);
            
        });
        // 返回上一页
        const goBack=()=>{
            router.go(-1)
        }
        // 构建搜索参数
        const buildSearchParams=()=> {
            Object.keys(state.selectedValues).forEach(key => {
                if (state.selectedValues[key]) {
                state.storyParams.inputConditions.push({
                    name: key,
                    value: state.selectedValues[key]
                })
                }
            });
        }
        // 获取初始筛选条件
        const getInitlookForData=()=>{
            StoryBoardGetMobileData(state.storyParams).then((res)=>{
                // console.log('后端返回的res',res.data);
                if(res.success==true ){
                    state.isShow=true
                    let lookForData=res.data.filter(item => item.controlType === "条件") || [];
                    state.lookForData=lookForData[0]?.returnData || [];
                }else{
                    state.isShow=false
                }
            })
            .catch((error) => {
                console.error("Error fetching data:", error);
            });    
        }
        // 获取我的数据条件筛选项
        const getInitDataList=()=>{
            // 更新分页参数
            state.storyParams.pageIndex = state.currentPage.toString();
            
            StoryBoardGetMobileData(state.storyParams).then((res)=>{
                // console.log('后端返回的res',res.data);
                let lookForData=res.data.filter(item => item.controlType === "条件") || [];
                state.lookForData=lookForData[0]?.returnData || [];
                
                let tableData=res.data.filter(item => item.controlType === "表格") || [];
                state.tableData=tableData[0]?.returnData || [];
                state.tableTitle=tableData[0]?.name || '';
                // 将完整数据集存储在 completeData 中
                // state.completeData = state.tableData;
                state.currentPageData = state.tableData;
                state.total = tableData[0].totalRows;
                state.itemsPerPage = tableData[0].pageSize;
                
                // 初始化当前页数据
                // updateCurrentPageData(1);
                // 设置分页组件的 total-items 属性
            })
            .catch((error) => {
                console.error("Error fetching data:", error);
            });            

        } 

        // 下拉刷新
        const onRefresh = () => {
            getInitDataList()
            state.isLoading = false
        }

        
        /**********************条件start**********************/ 
        const handleLabelClick = (item) => {
            console.log('item', item);
            state.currentItemId = item.id;
            pickerOptions.length= 0; // 清空现有数组
            // 在数组最前面添加一个空字符串选项
            pickerOptions.unshift({ text: '空', value: '' });
            // 添加新项
            item.optionsValue.forEach(inner => {
                let OptionsItem= { text: inner.key, value: inner.key }
                pickerOptions.push(OptionsItem)
            }); 
            
            state.showCalendar = true
        };
        // 取消
        const cancelPick = () => {
            state.showCalendar  = false
        }
        // 弹框确认选择（单选）
        const onPickerConfirm = (value) => {
            if (value.disabled) {
                state.showCalendar = false;
                return;
            }else{
                let id = state.currentItemId;
                // 更新 selectedValues
                state.selectedValues[id] = value.value;
                 // 检查是否有相同 id 的项，如果有则删除
                const existingIndex = state.storyParams.inputConditions.findIndex(condition => condition.name === id);
                if (existingIndex > -1) {
                    state.storyParams.inputConditions.splice(existingIndex, 1);
                }
                
                // 添加新的项
                state.storyParams.inputConditions.push({
                    name: id,
                    value: value.value
                })
                // console.log('查询参数',state.storyParams);
                
                state.currentPage=1; //当前页数要复原 
                // 触发搜索操作更新看板数据（更新total总数目）
                getInitDataList()
                state.showCalendar = false;
            }
            
        };
        // 弹框确认选择（多选）


        // 输入完成事件处理
        const handleInputBlur = (id) => {
            const value = state.selectedValues[id];
            // if (value) {
                // 更新 inputConditions
                const existingIndex = state.storyParams.inputConditions.findIndex(condition => condition.name === id);
                if (existingIndex > -1) {
                state.storyParams.inputConditions.splice(existingIndex, 1, { name: id, value });
                } else {
                state.storyParams.inputConditions.push({ name: id, value });
                }
                
                // 触发搜索操作更新看板数据
                getInitDataList();
            // }
        };
        // 清除输入框内容时触发
        const handleClear = (id) => {
            state.selectedValues[id] = ''; // 清除选中的值
            // 更新 inputConditions
            const existingIndex = state.storyParams.inputConditions.findIndex(condition => condition.name === id);
            if (existingIndex > -1) {
                state.storyParams.inputConditions.splice(existingIndex, 1);
            }
            
            // 触发搜索操作更新看板数据
            getInitDataList();
        };
        /**********************条件end**********************/ 

        // ===================分页器 start=======================
        // 更新当前页数据的方法
        const updateCurrentPageData = (page) => {
            const startIndex = (page - 1) * state.itemsPerPage;
            const endIndex = startIndex + state.itemsPerPage;
            state.currentPageData = state.completeData.slice(startIndex, endIndex);
        };
        
        // 监听currentPage的变化更新数据
        const onPageChange = (newPage) => {
            // 当currentPage变化时，调用更新数据的方法
            state.currentPage = newPage;
            state.storyParams.pageIndex = newPage.toString();
            // updateCurrentPageData(newPage);
            // 重新请求数据
            getInitDataList();
        };
        
        // 使用watch来监听 currentPage 的变化
        watch(() => state.currentPage, (newPage) => {
            // updateCurrentPageData(newPage);
            getInitDataList();
        }, { immediate: true });
        // ===================分页器 end=======================

        return {
            ...toRefs(state),
            ...toRefs(pickerOptions),
            // ...toRefs(chart),
            formData, 
            onRefresh,
            goBack,
            // 分页器
            onPageChange,
            // 条件
            computedPickerColumns,
            handleLabelClick,cancelPick,onPickerConfirm,
            handleInputBlur,handleClear,
            buildSearchParams,getInitlookForData

        };
    },
};

</script>

<style scoped>

</style>